﻿// This software is the confidential and proprietary information of NetBay.
// Such confidential information should not be disclosed.
// NetBay copyright(c) 2011

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Markup;
using NetBay.Core.BusinessEntities;
using NetBay.Core.BusinessEntities.Workflow;
using NetBay.Core.BusinessEntities.Workflow.Rules;
using Rio.Framework.Localisation;
using Rio.Framework.Pages.Context;
using Rio.Framework.Pages.Events;
using Rio.Framework.Pages.Manager;
using Telerik.Windows.Controls;
using Telerik.Windows.Data;
using Action = System.Action;

namespace Rio.Framework.Pages.Workflow
{
    public partial class WorkflowDashboardHistoric : INotifyPropertyChanged
    {
        #region Fields

        private WorkflowManager _workflowManager;

        public WorkflowManager WorkflowManager
        {
            get { return _workflowManager; }
            set
            {
                _workflowManager = value;
                OnPropertyChanged("WorkflowManager");

                if(WorkflowManager != null)
                    LoadHistoric();
            }
        }

        private ObservableCollection<WorkflowHisto> _workflowHiso = new ObservableCollection<WorkflowHisto>();

        #endregion

        #region Properties

        /// <summary>
        ///   Gets or sets the workflow historic.
        /// </summary>
        /// <value>The workflow historic.</value>
        public ObservableCollection<WorkflowInstance> WorkflowHistoric { get; set; }

        /// <summary>
        ///   Gets or sets the workflow histo.
        /// </summary>
        /// <value>The workflow histo.</value>
        public ObservableCollection<WorkflowHisto> WorkflowHisto
        {
            get { return _workflowHiso; }
            set
            {
                _workflowHiso = value;
                OnPropertyChanged("WorkflowHisto");
            }
        }

        #endregion

        public WorkflowDashboardHistoric()
        {
            InitializeComponent();

            Dispatcher.BeginInvoke(new Action(() => this.Language = XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.Name)));

            InitLabels();
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        /// <summary>
        ///   Loads the historic.
        /// </summary>
        public void LoadHistoric()
        {
            if (WorkflowManager.Folder != null &&
                WorkflowManager.Organization != null
                &&
                WorkflowManager.FolderType != null)
            {
                busyIndicator.IsBusy = true;

                FolderType folderType = GlobalWebContext.CurrentUser.GroupList.SelectMany(g => g.OrganizationList).SelectMany(o => o.FolderTypesList).Where(ft => ft.Identifier == WorkflowManager.Folder.FolderTypeIdentifier).FirstOrDefault();

                WorkflowManager.HistoricLoaded += WorkflowManagerHistoricLoaded;

                if(WorkflowManager.WorkflowInstance == null)
                {
                    WorkflowManager.LoadHistoric(folderType, WorkflowManager.Folder, GridHisto);   
                }
                else
                {
                    WorkflowManagerHistoricLoaded(new WorkflowHistoricEventArgs(
                                                      new List<WorkflowInstance>
                                                          {
                                                              WorkflowManager.WorkflowInstance
                                                          },
                                                      GridHisto));
                }
            }
        }

        /// <summary>
        ///   Called when [property changed].
        /// </summary>
        /// <param name = "propertyName">Name of the property.</param>
        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        /// <summary>
        ///   Inits the labels.
        /// </summary>
        private void InitLabels()
        {
            GridHisto.Columns["GridHisto_Etat"].Header = Resx.GetLabel(ResxFlowPage.STATE);
            GridHisto.Columns["GridHisto_FlowName"].Header = Resx.GetLabel(ResxWorkflow.FlowName);
            GridHisto.Columns["GridHisto_Date"].Header = Resx.GetLabel(ResxFlowPage.SENDINGDATE);
            GridHisto.Columns["GridHisto_TriggeredBy"].Header = Resx.GetLabel(ResxWorkflow.TriggeredBy);
            GridHisto.Columns["GridHisto_Event"].Header = Resx.GetLabel(ResxWorkflow.EventSource);
            GridHisto.Columns["GridHisto_Receivers"].Header = Resx.GetLabel(ResxWorkflow.SendTo);
            GridHisto.Columns["GridHisto_Receiver"].Header = Resx.GetLabel(ResxWorkflow.Receiver);
        }

        /// <summary>
        ///   Workflows the manager_ historic loaded.
        /// </summary>
        /// <param name = "args">The <see cref = "Rio.Framework.Pages.Events.WorkflowHistoricEventArgs" /> instance containing the event data.</param>
        private void WorkflowManagerHistoricLoaded(WorkflowHistoricEventArgs args)
        {
            WorkflowManager.HistoricLoaded -= WorkflowManagerHistoricLoaded;

            if (args.Historic != null)
            {
                WorkflowHistoric = new ObservableCollection<WorkflowInstance>(args.Historic.OrderBy(i => i.CreatedOn));
                OnPropertyChanged("WorkflowHistoric");
            }

            busyIndicator.IsBusy = false;
        }

        /// <summary>
        ///   Handles the Loaded event of the DocumentsDetail control.
        /// </summary>
        /// <param name = "sender">The source of the event.</param>
        /// <param name = "e">The <see cref = "System.Windows.RoutedEventArgs" /> instance containing the event data.</param>
        private void DocumentsDetailLoaded(object sender, RoutedEventArgs e)
        {
            RadGridView gridViewSource = sender as RadGridView;

            if (gridViewSource != null)
            {
                gridViewSource.IsBusy = true;

                WorkflowInstance workflowInstanceSource = gridViewSource.DataContext as WorkflowInstance;
                WorkflowManager.HistoricForInstanceLoaded += WorkflowManagerHistoricForInstanceLoaded;
                WorkflowManager.LoadHistoricForInstance(workflowInstanceSource, gridViewSource);
            }
        }

        /// <summary>
        ///   _workflows the manager_ historic for instance loaded.
        /// </summary>
        /// <param name = "args">The <see cref = "Rio.Framework.Pages.Events.WorkflowHistoricEventArgs" /> instance containing the event data.</param>
        private void WorkflowManagerHistoricForInstanceLoaded(WorkflowHistoricEventArgs args)
        {
            WorkflowManager.HistoricForInstanceLoaded -= WorkflowManagerHistoricForInstanceLoaded;

            RadGridView gridViewSource = args.Sender as RadGridView;
            if (gridViewSource != null)
            {
                gridViewSource.IsBusy = false;

                if (args.HistoricForInstance != null)
                {
                    gridViewSource.ItemsSource = new QueryableCollectionView(args.HistoricForInstance.OrderBy(i => i.Name).ToList());
                }
            }
        }

        /// <summary>
        ///   Handles the Loaded event of the DocumentHistoricGridView control.
        /// </summary>
        /// <param name = "sender">The source of the event.</param>
        /// <param name = "e">The <see cref = "System.Windows.RoutedEventArgs" /> instance containing the event data.</param>
        private void DocumentHistoricGridViewLoaded(object sender, RoutedEventArgs e)
        {
            RadGridView gridViewSource = sender as RadGridView;

            if (gridViewSource != null)
            {
                gridViewSource.Columns["DocumentHistoricGridView_DateAction"].Header =
                    Resx.GetLabel(ResxFlowPage.DATE);
                gridViewSource.Columns["DocumentHistoricGridView_Actionlabel"].Header =
                    Resx.GetLabel(ResxWorkflow.FlowAction);
                gridViewSource.Columns["DocumentHistoricGridView_HistoUserFullName"].Header =
                    Resx.GetLabel(ResxCommon.USER);
                gridViewSource.Columns["DocumentHistoricGridView_HistoGroupName"].Header =
                    Resx.GetLabel(ResxCommon.GROUPS);
                gridViewSource.Columns["DocumentHistoricGridView_Comment"].Header = Resx.GetLabel(
                    ResxFlowPage.MEMO);

                //Only if the item is a document
                if (gridViewSource.DataContext is WorkflowDocument)
                {
                    gridViewSource.IsBusy = true;

                    WorkflowDocument documentStateSource = gridViewSource.DataContext as WorkflowDocument;

                    WorkflowManager.HistoricForDocumentLoaded += WorkflowManagerHistoricForDocumentLoaded;
                    WorkflowManager.LoadHistoricForDocument(documentStateSource, gridViewSource);
                }
            }
        }

        /// <summary>
        ///   _workflows the manager_ historic for document loaded.
        /// </summary>
        /// <param name = "args">The <see cref = "Rio.Framework.Pages.Events.WorkflowHistoricEventArgs" /> instance containing the event data.</param>
        private void WorkflowManagerHistoricForDocumentLoaded(WorkflowHistoricEventArgs args)
        {
            WorkflowManager.HistoricForDocumentLoaded -= WorkflowManagerHistoricForDocumentLoaded;

            RadGridView gridViewSource = args.Sender as RadGridView;
            if (gridViewSource != null)
            {
                gridViewSource.IsBusy = false;

                if (args.HistoricForDocument != null && gridViewSource.DataContext is WorkflowDocument)
                {
                    WorkflowDocument documentStateSource = gridViewSource.DataContext as WorkflowDocument;

                    gridViewSource.ItemsSource = new QueryableCollectionView(args.HistoricForDocument.Where(i => i.InstanceIdentifier == documentStateSource.InstanceId).OrderByDescending(i => i.DateAction).ToList());
                }
            }
        }
    }
}